﻿using DeployTool.Core;
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace DeployTool.CustomControl
{
    public partial class SqlserverUserControl : UserControl, IDeployStep
    {
        readonly string _rootDir;
        readonly string _configPath;
        readonly string _initsqlPath;
        public SqlserverUserControl()
        {
            InitializeComponent();
            _rootDir = Tool.GetRootDir();
            _configPath = Path.Combine(_rootDir, "wlwsys_intranet/configs/appsettings.json");
            _initsqlPath = Path.Combine(_rootDir, "database/init.sql");
        }

        #region IDeployStep
        public StepEnum Step { get; set; } = StepEnum.First;

        public bool CanNextStep()
        {
            return true;
        }

        public void RefreshData()
        {
            InitData();
        }
        #endregion

        #region private methods
        /// <summary>
        /// 初始相关数据
        /// </summary>
        private void InitData()
        {
            string result = Tool.StartProgramWithResult("sc", "query MSSQLSERVER");
            if (result.Contains("SERVICE_NAME: MSSQLSERVER"))
            {
                InitSqlState(result);
                return;
            }
            else
            {
                result = Tool.StartProgramWithResult("sc", "query SQLEXPRESS");
                if (result.Contains("SERVICE_NAME: SQLEXPRESS"))
                {
                    InitSqlState(result);
                    return;
                }
            }

            UpdateSqlButton(false, "未安装");
        }

        /// <summary>
        /// 更新数据库功能按钮状态
        /// </summary>
        /// <param name="isEnable">是否启用</param>
        /// <param name="text">数据库状态文本</param>
        private void UpdateSqlButton(bool isEnable, string text)
        {
            btn_server_status.Enabled = isEnable;
            btn_server_status.Text = $"数据库状态：{text}";
            //if (!isEnable)
            //{
            //    btn_connect.Enabled = isEnable;
            //    btn_init.Enabled = isEnable;
            //    btn_sql.Enabled = isEnable;
            //}
        }

        /// <summary>
        /// 初始化sql状态
        /// </summary>
        /// <param name="result">sql状态查询结果</param>
        private void InitSqlState(string result)
        {
            if (result.Contains("STATE") && result.Contains("RUNNING"))
            {
                UpdateSqlButton(true, "运行中");
            }
            else
            {
                UpdateSqlButton(true, "已停止");
            }
        }

        /// <summary>
        /// sqlser数据库链接
        /// </summary>
        private string ToSqlConnectionStr()
        {
            return $"user id={txt_user.Text};password={txt_password.Text};initial catalog=wlwsys;data source={txt_host.Text},{txt_port.Text};Connect Timeout=30;";
        }

        /// <summary>
        /// 状态事件函数
        /// </summary>
        private void btn_server_status_Click(object sender, EventArgs e)
        {
            if (btn_server_status.Text.Contains("运行中"))
            {
                string result = Tool.StartProgramWithResult("sc", "stop MSSQLSERVER");
                if (result.Contains("SERVICE_NAME: MSSQLSERVER") || result.Contains("ControlService 失败 1062"))
                {
                    btn_server_status.Text = $"数据库状态：已停止";
                    return;
                }

                string result1 = Tool.StartProgramWithResult("sc", "stop SQLEXPRESS");
                if (result.Contains("SERVICE_NAME: SQLEXPRESS") || result.Contains("ControlService 失败 1062"))
                {
                    btn_server_status.Text = $"数据库状态：已停止";
                    return;
                }

                throw new BusinessException($"{result}{Environment.NewLine}{result1}");
            }
            else
            {
                string result = Tool.StartProgramWithResult("sc", "start MSSQLSERVER");
                if (result.Contains("SERVICE_NAME: MSSQLSERVER") || result.Contains("StartService 失败 1056"))
                {
                    btn_server_status.Text = $"数据库状态：运行中";
                    return;
                }

                string result1 = Tool.StartProgramWithResult("sc", "start SQLEXPRESS");
                if (result.Contains("SERVICE_NAME: SQLEXPRESS") || result.Contains("StartService 失败 1056"))
                {
                    btn_server_status.Text = $"数据库状态：运行中";
                    return;
                }

                throw new BusinessException($"{result}{Environment.NewLine}{result1}");
            }
        }

        private void btn_Click(object sender, EventArgs e)
        {
            string connection = ToSqlConnectionStr();
            Button btn = sender as Button;
            switch (btn.Name)
            {
                case "btn_connect":
                    {
                        Tool.ExecuteSql(connection, null, true);
                        //更改配置文件数据库链接
                        Newtonsoft.Json.Linq.JObject config = Tool.LoadJsonFile(_configPath);
                        config["PublishConfig"]["Public"]["db"]["ConnString"] = connection;
                        config["PublishConfig"]["Test"]["db"]["ConnString"] = connection;
                        Tool.SaveFile(config.ToString(), _configPath);
                        throw new BusinessException("数据库连接成功");
                    }
                case "btn_init":
                    {
                        string sql = Tool.ReadFile(_initsqlPath);
                        Tool.ExecuteSql(connection, sql);
                        throw new BusinessException("sql脚本初始成功");
                    }
                case "btn_sql":
                    {
                        OpenFileDialog openFileDialog = new OpenFileDialog();
                        openFileDialog.InitialDirectory = _rootDir;
                        openFileDialog.AddExtension = true;
                        openFileDialog.CheckFileExists = true;
                        openFileDialog.CheckPathExists = true;
                        openFileDialog.Multiselect = false;
                        DialogResult dialogResult = openFileDialog.ShowDialog();
                        if (dialogResult == DialogResult.OK || dialogResult == DialogResult.Yes)
                        {
                            using (Stream stream = openFileDialog.OpenFile())
                            {
                                using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
                                {
                                    string sql = sr.ReadToEnd();
                                    Tool.ExecuteSql(connection, sql);
                                    throw new BusinessException("sql脚本执行成功");
                                }
                            }
                        }
                    }
                    break;
            }
        }
        #endregion
    }
}
